package com.fruitbasket.audioplatform;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import static android.app.Activity.RESULT_OK;

public class FirstFragment extends Fragment {


    private static final int REQUEST_TAKE_PHOTO_CODE = 1;
    private String TAG = "xianjian";
    public Context context = ContextUtil.getContext();
    private  final  static int REQ_CODE = 1;
    private  final  String FILE_PROVIDER_AUTHORITY = "com.fruitbasket.audioplatform.fileProvider";
    ImageView mPicture;
    Uri mImageUri;


    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false);
    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        /*pop this view*/
        mPicture = view.findViewById(R.id.image_first);

//        view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                NavHostFragment.findNavController(FirstFragment.this)
//                        .navigate(R.id.action_FirstFragment_to_SecondFragment);
//            }
//        });
//        view.findViewById(R.id.button_setting).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                NavHostFragment.findNavController(FirstFragment.this)
//                        .navigate(R.id.action_FirstFragment_to_SettingFragment);
//            }
//        });

        view.findViewById(R.id.takephoto_first).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                takePhoto();
            }
        });

        view.findViewById(R.id.compress_pic).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        compress_pic();
                    }
                }).start();
            }
        });

        view.findViewById(R.id.button_startService).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               start_calculate();
            }
        });
    }

    public void start_calculate() {
        //start calculate service
        Intent IntentCalculate = new Intent(context, CalculateService.class);
        context.startService( IntentCalculate);
    }

    public void compress_pic(){
        try {
            Bitmap bitmap           = BitmapFactory.decodeStream( context.getContentResolver().openInputStream(mImageUri) );
            //Bitmap bitmaptmp        = ImageCompressUtil.compressByQuality( bitmap, 100 );
            Bitmap bitmaptmp        = ImageCompressUtil.compressBySize( bitmap, 2000,1800 );
            File file               = new File( context.getExternalFilesDir(null), "input2.jpg");
            FileOutputStream fOut   = new FileOutputStream( file );
            bitmaptmp.compress( Bitmap.CompressFormat.JPEG, 100, fOut );
            fOut.flush();
            fOut.close();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void takePhoto(){
        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//打开相机的Intent
        if(takePhotoIntent.resolveActivity(context.getPackageManager())!=null){//这句作用是如果没有相机则该应用不会闪退，要是不加这句则当系统没有相机应用的时候该应用会闪退
            File imageFile = createImageFile();//创建用来保存照片的文件
            if(imageFile!=null){
                /*7.0以上要通过FileProvider将File转化为Uri*/
                //Uri mImageUri = FileProvider.getUriForFile(this, FILE_PROVIDER_AUTHORITY, imageFile);
                mImageUri = FileProvider.getUriForFile(context, FILE_PROVIDER_AUTHORITY, imageFile);
                takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);//将用于输出的文件Uri传递给相机
                //startActivityForResult(takePhotoIntent, REQUEST_TAKE_PHOTO_CODE);//打开相机
                startActivityForResult(takePhotoIntent, REQUEST_TAKE_PHOTO_CODE);//打开相机
            }
        }
    }
    /**
     * 创建用来存储图片的文件，以时间来命名就不会产生命名冲突
     * @return 创建的图片文件
     */
    private File createImageFile() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "input_"+timeStamp+"_";
        File storageDir = context.getExternalFilesDir(null);
        File imageFile = null;
        try {
            imageFile = File.createTempFile(imageFileName,".jpg",storageDir);
            Log.i(TAG, ">>>>>>createImageFile>>>>>>>"+imageFile.getAbsolutePath());
            SharedPreferences sharedPreferences= context.getSharedPreferences("userData",Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("tmpfile", imageFile.getAbsolutePath());
            editor.commit();

        } catch (IOException e) {
            e.printStackTrace();
        }
        //return imageFile.renameTo(new File(storageDir+"/input3.jpg"));

        return imageFile;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode== 1 &&resultCode==RESULT_OK){
            try {
                /*如果拍照成功，将Uri用BitmapFactory的decodeStream方法转为Bitmap*/
                Bitmap bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(mImageUri));
                mPicture.setImageBitmap(bitmap);//显示到ImageView上
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onResume() {
        Log.i(TAG,"first fragment on resume resume imageview");
        try {
            Bitmap bitmap2 = BitmapFactory.decodeStream(new FileInputStream(context.getExternalFilesDir(null)+"/input2.jpg"));
            mPicture.setImageBitmap(bitmap2);
        }catch (IOException e) {
            e.printStackTrace();
        }
        Log.i(TAG,"first fragment on resume");
        super.onResume();
    }
}